layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage','tree'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		tree =layui.tree;
		$ = layui.jquery;

	//查询树
	$.get("/author/getTree.do",function(data){
		//console.log(data);
		tree({
			elem: '#authorTree' //传入元素选择器
			,nodes:data,
			click: function (node) {
				var $select = $($(this)[0].elem).parents(".layui-form-select");
				$select.removeClass("layui-form-selected").find(".layui-select-title span").html(node.name).end().find("input:hidden[name='authorId']").val(node.id);
			}
		});
		$(".downpanel").on("click", ".layui-select-title", function (e) {
			$(".layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
			$(this).parents(".downpanel").toggleClass("layui-form-selected");
			layui.stope(e);
		}).on("click", "dl i", function (e) {
			layui.stope(e);
		});
		$(document).on("click", function (e) {
			$(".layui-form-select").removeClass("layui-form-selected");
		});
	});




	//加载页面数据
	var searchkeys = {};

	//初次加载页面
	function init(curr) {
		searchkeys.searchKey = $(".search_input").val().trim();
		searchkeys.authorId = $("#authorId").val().trim();
		searchkeys.currentPage =  curr!=undefined?curr:1;
		searchkeys.rows = 20;
		console.log(JSON.stringify(searchkeys));
		$.ajax({
			url: "/author/select.do",
			type: "post",
			contentType: "application/json;charset=utf-8",
			dataType: "json",
			data: JSON.stringify(searchkeys),
			success: function (data) {
				commonList(data,data.list);
			}
		})
	}
	init();

	//查询
	$(".search_btn").click(function(){

		//查询条件对象
		searchkeys.searchKey=$(".search_input").val().trim();
		searchkeys.authorId=$("#authorId").val().trim();
		searchkeys.currentPage=1;
		searchkeys.rows=20;

		console.log(JSON.stringify(searchkeys));

		var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
		$.ajax({
			url : "/author/select.do",
			type : "post",
			contentType:"application/json;charset=utf-8",
			dataType : "json",
			data:JSON.stringify(searchkeys),
			success : function(data){
				layer.close(index);
				commonList(data,data.list);
			}
		})
	})

	//添加类别
	//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
	$(window).one("resize",function(){
		$(".commonAdd_btn").click(function(){
			var index = layui.layer.open({
				title : "添加",
				type : 2,
				content : "authorAdd.html",
				success : function(layero, index){
					setTimeout(function(){
						layui.layer.tips('点击此处返回类别列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
					},500)
				}
			})			
			layui.layer.full(index);
		})
	}).resize();

	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.common_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.common_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var ids=[];
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
				for(var j=0;j<$checked.length;j++){
					var tempId = $checked.eq(j).parents("tr").find(".common_del").attr("data-id");
					ids.push(tempId);
				}
				$.get("/category/deleteMany.do",{"ids":ids},function(data){
					$('.common_list thead input[type="checkbox"]').prop("checked",false);
					form.render();
					layer.close(index);
					layer.msg("删除成功");
					init(searchkeys.currentPage);
				})
	        })
		}else{
			layer.msg("请选择需要删除的用户");
		}
	})

	//全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="status"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断类型是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})


 
	//编辑操作

	$("body").on("click",".common_edit",function(){
		var tempId = $(this).data("id");
		var index = layui.layer.open({
			title : "编辑",
			type : 2,
			content : "authorUpdate.html#"+tempId,
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回类别列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		})
		layui.layer.full(index);
	});


	//删除
	$("body").on("click",".common_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
			//发送ajax删除数据
			$.get("/author/delete.do",{"id":_this.data("id")}, function(data){
				   if(data.status){
					   //_this.parents("tr").remove();
					   init(searchkeys.currentPage);
					   layer.close(index);
				   }
			})

		});
	})

    //渲染列表(分页+数据+条件查询)
	function commonList(returnData,commonData){
		function renderDate(commonData){
			var dataHtml = '';
			if(commonData.length != 0){
				for(var i=0;i<commonData.length;i++){
					dataHtml += '<tr>'
			    	+'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
			    	+'<td>'+commonData[i].id+'</td>'
			    	+'<td>'+commonData[i].title+'</td>';
					if(commonData[i].parent==null){
						dataHtml += '<td>无</td>';
					}else{
						dataHtml += '<td>'+commonData[i].parent.title+'</td>';
					}
					if(commonData[i].type=="0"){
						dataHtml +='<td>所有人开放</td>';
					}else if(commonData[i].type=="1"){
						dataHtml +='<td>菜单权限</td>';
					}else if(commonData[i].type=="2"){
						dataHtml +='<td>按钮权限</td>';
					}
					dataHtml +='<td>'+commonData[i].url+'</td>';

			    	dataHtml += ''
			    	+'<td>'
					+  '<a class="layui-btn layui-btn-mini common_edit" data-id="'+commonData[i].id+'"><i class="iconfont icon-edit"></i> 编辑</a>'
					+  '<a class="layui-btn layui-btn-normal layui-btn-mini common_detail" data-id="'+commonData[i].id+'"><i class="layui-icon">&#xe600;</i> 详情</a>'
					+  '<a class="layui-btn layui-btn-danger layui-btn-mini common_del" data-id="'+commonData[i].id+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
			        +'</td>'
			    	+'</tr>';
				}
			}else{
				dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
			}
		    return dataHtml;
		}
		//分页
		laypage({
			cont : "page",
			pages : returnData.pages,
			jump : function(obj,first){

				searchkeys.currentPage=obj.curr; //当前页
				searchkeys.rows=20; //每页出现的数据量
				if(!first){
					$.ajax({
						url : "/author/select.do",
						type : "post",
						contentType:"application/json;charset=utf-8",
						dataType : "json",
						data:JSON.stringify(searchkeys),
						success : function(data){
							$(".common_content").html(renderDate(data.list));
							$('.common_list thead input[type="checkbox"]').prop("checked",false);
							form.render();
						}
					})
				}else{
					$(".common_content").html(renderDate(commonData));
					$('.common_list thead input[type="checkbox"]').prop("checked",false);
					form.render();
				}

			}
		})
	}
})
